<?php
/**
 * Created by PhpStorm.
 * User: CPR065
 * Date: 2016/10/9
 * Time: 10:10
 */

namespace Common\Common;


class Prize {
    public $totalNum = 100; //奖池总数
    public function getPrize(){

        $prizeInfo = $this->getPrizeList();
        $prizeList = $prizeInfo['list'];
        $prizeGL = $prizeInfo['gailv'];//奖品概率
        $result=$this->getRand($prizeGL);

        echo $prizeList[$result]['name'];
    }
    public function getPrizeList(){

        $prize=array(
            array('id'=>1,'name'=>'苹果电脑','chance'=>1),
            array('id'=>2,'name'=>'苹果手机','chance'=>2),
            array('id'=>3,'name'=>'1000元购物卡','chance'=>3),
            array('id'=>4,'name'=>'300元餐具','chance'=>4),
            array('id'=>5,'name'=>'100元手机充值卡','chance'=>5)
        );
        $prize_form[0]=array('id'=>0,'name'=>'谢谢参与！');
        foreach ($prize as $key => $value) {
            //格式化数组
            $prize_form[$value['id']]=$value;
            if($value['chance']>0){
                $p[$value['id']]=$value['chance'];
            }
        }
        $result['list'] = $prize_form;
        $result['gailv'] = $p;
        return $result;
    }
    /*
    *奖项的ID不得为0,0默认为谢谢参与
    *$proArr=array('1'=>'1','2'=>2)
    **/

    private function getRand($proArr)
    {
        //奖项数量
        $prize_number=count($proArr);
        foreach ($proArr as $key => $value) {
            for($i=0;$i<$value;$i++){
                //生成得奖球
                $seekGroup[]='P'.$key;

            }
        }

        $chance_sum=array_sum($proArr);
        //干扰球数量
        $disturb_number= $this->totalNum-$chance_sum;
        //生成干扰球
        $disturb=range(1,$disturb_number);
        //将球放入篮子里
        $basket=array_merge($seekGroup,$disturb);
        shuffle($basket);
        //抽奖
        $rand=rand(0,$this->totalNum-1);
        if(strstr($basket[$rand], "P")){
            $result=str_replace('P', '', $basket[$rand]);
        }else{
            $result=0;
        }

        return $result;
    }
} 